#!/usr/bin/env python
# -*- coding: utf-8 -*-
__author__ = 'tian'
__data__ = '2021/9/30 11:24'
# software: PyCharm

from django import forms
from django.forms import widgets
from django.core.exceptions import ValidationError

from apps.web.forms.bootstrap import BootStrapForm
from apps.web.forms.widgets import ColorRadioSelect
from apps.web import models


class ProjectModeForm(BootStrapForm, forms.ModelForm):
    bootstrap_class_exclude = ['color']  # color不使用BootStrap样式

    def __init__(self, request, *args, **kwargs):
        super().__init__(*args, **kwargs)
        self.request = request

    class Meta:
        model = models.Project
        fields = ["name", "color", "desc"]
        widgets = {
            "desc": forms.Textarea,
            "color": ColorRadioSelect(attrs={"class": "color-radio"})
        }

    def clean_name(self):
        """
        项目校验
        :return:
        """
        name = self.cleaned_data.get("name")
        # 当前用户是否已经创建过此项目(项目名是否已存在)
        exists = models.Project.objects.filter(name=name, creator=self.request.tracer.user).exists()
        if exists:
            raise ValidationError("项目已经存在")
        # 当前用户是否还有额度创建项目
        # 最多创建多少个项目? 当前用户已经创建多少个项目? 查询后进行判断。
        count = models.Project.objects.filter(creator=self.request.tracer.user).count()
        if count >= self.request.tracer.price_policy.project_num:
            raise ValidationError("项目个数超限,请购买套餐")
        return name
